package cn.tedu.eguser1.controller;

import cn.tedu.eguser1.base.response.JsonResult;
import cn.tedu.eguser1.base.response.StatusCode;
import cn.tedu.eguser1.mapper.UserMapper;
import cn.tedu.eguser1.pojo.dto.UserAddParam;
import cn.tedu.eguser1.pojo.dto.UserLoginParam;
import cn.tedu.eguser1.pojo.dto.UserUpdateParam;
import cn.tedu.eguser1.pojo.entity.User;
import cn.tedu.eguser1.pojo.vo.UserListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Validated
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;


    @PostMapping("/add")
    @ApiOperationSupport(order = 10)
    @Operation(summary = "添加用户")
    public JsonResult add(@RequestBody @Validated UserAddParam userAddParam) {
        System.out.println("userAddParam = " + userAddParam);
        User user = new User();
        BeanUtils.copyProperties(userAddParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int num = userMapper.insertUser(user);
        if (num > 0) {
           return JsonResult.ok(user);
        }
        return new JsonResult(StatusCode.OPERATION_FAIL);
    }

    @GetMapping("/list")
    public JsonResult list() {
        List<UserListVO> userListVOS = userMapper.listUser();
        System.out.println("userListVOS =" + userListVOS);
        return JsonResult.ok(userListVOS);
    }

    @PostMapping("/del/{id}")
    public JsonResult del(@PathVariable @Range(min = 1L, max = 100L, message = "用户id要在1到100之间") Long id) {
        int num = userMapper.deleteUserById(id);
        if (num > 0) {
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.OPERATION_FAIL);
    }

    @PostMapping("/update")
    public JsonResult update(@RequestBody UserUpdateParam userUpdateParam) {
        System.out.println("userUpdateParam = " + userUpdateParam);
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);
        int num = userMapper.updateUserById(user);
        if (num > 0) {
            return JsonResult.ok(user);
        }
        return new JsonResult(StatusCode.OPERATION_FAIL);
    }

    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam) {
        System.out.println("userLoginParam = " + userLoginParam);
        return JsonResult.ok();
    }
}
